<template>
  <div class="app-container">
    <div class="module-title">
      <svg-icon icon-class="shopping" style="font-size:28px;margin-right:8px;"/>
      <span>生产领料</span>
      <span class="module-desc">管理生产领料单据与明细</span>
    </div>
    <div class="module-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="单据名称" prop="documentName">
          <el-input
            v-model="queryParams.documentName"
            placeholder="请输入单据名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input
            v-model="queryParams.materialName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="goAddPage"
            v-hasPermi="['picking:picking:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['picking:picking:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['picking:picking:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['picking:picking:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-s-order"
            size="mini"
            @click="handleImportFromWorkOrder"
            v-hasPermi="['picking:picking:import']"
          >从工单导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-s-order"
            size="mini"
            @click="handleGoToReceipt"
            v-hasPermi="['picking:picking:generate-receipt']"
          >转入入库管理</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="pickingList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="领料单ID" align="center" prop="issueId" />
        <el-table-column label="工单ID" align="center" prop="orderId" />
        <el-table-column label="物料编码" align="center" prop="materialId" />
        <el-table-column label="单据名称" align="center" prop="documentName" />
        <el-table-column label="审核状态" align="center" prop="reviewStatus">
          <template slot-scope="scope">
            <el-tag :type="getReviewStatusType(scope.row.reviewStatus)">
              {{ scope.row.reviewStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="领料日期" align="center" prop="issueDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="物料规格" align="center" prop="specification" />
        <el-table-column label="物料名称" align="center" prop="materialName" />
        <el-table-column label="需求数量" align="center" prop="requiredQty" />
        <el-table-column label="实际领料数量" align="center" prop="issuedQty" />
        <el-table-column label="单据编号" align="center" prop="documentNumber" />
        <el-table-column label="物料单位" align="center" prop="materialUnit" />
        <el-table-column label="备注" align="center" prop="remarks" />
        <el-table-column label="创建人" align="center" prop="creator" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['picking:picking:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['picking:picking:remove']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-order"
              @click="handleGoToReceiptFromRow(scope.row)"
              v-hasPermi="['picking:picking:generate-receipt']"
            >转入入库管理</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改生产领料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入工单ID" />
        </el-form-item>
        <el-form-item label="物料编码" prop="materialId">
          <el-input v-model="form.materialId" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="单据名称" prop="documentName">
          <el-input v-model="form.documentName" placeholder="请输入单据名称" />
        </el-form-item>
        <el-form-item label="领料日期" prop="issueDate">
          <el-date-picker clearable
            v-model="form.issueDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择领料日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="物料规格" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入物料规格" />
        </el-form-item>
        <el-form-item label="审核状态" prop="reviewStatus">
          <el-input v-model="form.reviewStatus" placeholder="审核状态" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="需求数量" prop="requiredQty">
          <el-input v-model="form.requiredQty" placeholder="请输入需求数量" />
        </el-form-item>
        <el-form-item label="实际领料数量" prop="issuedQty">
          <el-input v-model="form.issuedQty" placeholder="请输入实际领料数量" />
        </el-form-item>
        <el-form-item label="单据编号" prop="documentNumber">
          <el-input v-model="form.documentNumber" placeholder="请输入单据编号" />
        </el-form-item>
        <el-form-item label="物料单位" prop="materialUnit">
          <el-input v-model="form.materialUnit" placeholder="请输入物料单位" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
      </el-form>
      <div style="margin: 16px 0 0 0;">
        <picking-detail-table v-model="form.details" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPicking, getPicking, delPicking, addPicking, updatePicking } from "@/api/picking/picking"
import { listPicking_detail } from '@/api/picking_detail/picking_detail'
import { addReceipt } from "@/api/receipt/receipt"
import PickingDetailTable from '@/views/picking_detail/picking_detail/PickingDetailTable.vue'

export default {
  activated(){
    this.getList()
  },
  name: "Picking",
  components: { PickingDetailTable },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产领料表格数据
      pickingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        documentName: null,
        materialName: null,
      },
      // 表单参数
      form: {
        issueId: null,
        orderId: null,
        materialId: null,
        documentName: null,
        reviewStatus: null,
        issueDate: null,
        specification: null,
        materialName: null,
        requiredQty: null,
        issuedQty: null,
        documentNumber: null,
        materialUnit: null,
        remarks: null,
        creator: null,
        createTime: null,
        details: [] // 子表数据
      },
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询生产领料列表 */
    getList() {
      this.loading = true
      listPicking(this.queryParams).then(response => {
        this.pickingList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        issueId: null,
        orderId: null,
        materialId: null,
        documentName: null,
        reviewStatus: null,
        issueDate: null,
        specification: null,
        materialName: null,
        requiredQty: null,
        issuedQty: null,
        documentNumber: null,
        materialUnit: null,
        remarks: null,
        creator: null,
        createTime: null,
        details: [] // 子表数据
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.issueId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    goAddPage() {
      this.$router.push({ path: '/picking/picking/add' });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const issueId = row.issueId || this.ids
      getPicking(issueId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改生产领料"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.issueId != null) {
            updatePicking(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPicking(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const issueIds = row.issueId || this.ids
      this.$modal.confirm('是否确认删除生产领料编号为"' + issueIds + '"的数据项？').then(function() {
        return delPicking(issueIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('picking/picking/export', {
        ...this.queryParams
      }, `picking_${new Date().getTime()}.xlsx`)
    },
    /** 从工单导入按钮操作 */
    handleImportFromWorkOrder() {
      this.$router.push('/picking/picking/import-from-work-order');
    },
    /** 转入入库管理按钮操作 */
    handleGoToReceipt() {
      if (this.ids.length === 0) {
        this.$modal.msgError('请选择要转入入库管理的生产领料单')
        return
      }
      const selectedPicking = this.pickingList.filter(item => this.ids.includes(item.issueId))
      if (selectedPicking.length === 0) {
        this.$modal.msgError('未找到对应的生产领料单')
        return
      }
      
      // 构建要转入的入库数据
      const receiptData = {
        documentNumber: parseInt(Date.now().toString().slice(-9)) + Math.floor(Math.random() * 1000),
        documentName: '生产入库单',
        receiptType: '生产入库',
        workOrder: selectedPicking[0].orderId,
        materialId: selectedPicking[0].materialId,
        materialName: selectedPicking[0].materialName,
        specification: selectedPicking[0].specification,
        materialUnit: selectedPicking[0].materialUnit,
        receiptQuantity: selectedPicking[0].issuedQty,
        documentType: '生产入库单',
        remarks: `从生产领料单 ${selectedPicking[0].documentNumber} 转入`,
        creator: this.$store.getters.name
      }
      
      // 确认是否转入
      this.$modal.confirm(`是否确认将生产领料单"${selectedPicking[0].documentNumber}"转入入库管理？`).then(() => {
        // 先调用API添加入库单
        return addReceipt(receiptData)
      }).then(() => {
        // 转入成功后显示成功消息
        this.$modal.msgSuccess("转入入库管理成功！")
        // 刷新列表
        this.getList()
        // 跳转到生产入库管理页面
        this.$router.push('/receipt/receipt')
      }).catch((error) => {
        console.error('转入失败:', error)
        this.$modal.msgError("转入入库管理失败，请重试")
      })
    },
    /** 转入入库管理按钮操作 (单行) */
    handleGoToReceiptFromRow(row) {
      // 构建要转入的入库数据
      const receiptData = {
        documentNumber: parseInt(Date.now().toString().slice(-9)) + Math.floor(Math.random() * 1000),
        documentName: '生产入库单',
        receiptType: '生产入库',
        workOrder: row.orderId,
        materialId: row.materialId,
        materialName: row.materialName,
        specification: row.specification,
        materialUnit: row.materialUnit,
        receiptQuantity: row.issuedQty,
        documentType: '生产入库单',
        remarks: `从生产领料单 ${row.documentNumber} 转入`,
        creator: this.$store.getters.name
      }
      
      // 确认是否转入
      this.$modal.confirm(`是否确认将生产领料单"${row.documentNumber}"转入入库管理？`).then(() => {
        // 先调用API添加入库单
        return addReceipt(receiptData)
      }).then(() => {
        // 转入成功后显示成功消息
        this.$modal.msgSuccess("转入入库管理成功！")
        // 刷新列表
        this.getList()
        // 跳转到生产入库管理页面
        this.$router.push('/receipt/receipt')
      }).catch((error) => {
        console.error('转入失败:', error)
        this.$modal.msgError("转入入库管理失败，请重试")
      })
    },
    /** 获取审核状态标签类型 */
    getReviewStatusType(status) {
      switch(status) {
        case '已审核':
          return 'success'
        case '待审核':
          return 'warning'
        case '已拒绝':
          return 'danger'
        default:
          return 'info'
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "~@/assets/styles/module-card.scss";

.module-title {
  display: flex;
  align-items: center;
  font-size: 22px;
  font-weight: 700;
  color: #2980b9;
  margin-bottom: 18px;
  .module-desc {
    font-size: 14px;
    color: #888;
    font-weight: 400;
    margin-left: 18px;
  }
}

.el-table {
  .el-table__body tr:hover > td {
    background: #eaf6ff !important;
  }
}
</style>
